from django.utils.deprecation import MiddlewareMixin
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django.http import JsonResponse
from rest_framework import status


class DebugCorsMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print("Entering DebugCorsMiddleware.process_request")
        print(f"Request headers in DebugCorsMiddleware: {request.headers}")
        return None

    def process_response(self, request, response):
        print("Entering DebugCorsMiddleware.process_response")
        print(f"Response status code in DebugCorsMiddleware: {response.status_code}")
        return response


class DebugJWTAuthentication(JSONWebTokenAuthentication):
    def authenticate(self, request):
        print("Entering DebugJWTAuthentication.authenticate")
        print(f"Request headers in DebugJWTAuthentication: {request.headers}")
        try:
            result = super().authenticate(request)
            if result is None:
                print("JWT authentication failed.")
            return result
        except Exception as e:
            print(f"JWT authentication error: {e}")
            return JsonResponse({'error': 'JWT authentication error'}, status=status.HTTP_401_UNAUTHORIZED)